package com.defysoft.waukids.message;

import java.util.ArrayList;

import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Custom_Data_Type.WK_MESSAGE_LIST;
import com.defysoft.waukids.Data_Sharedpreferences;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.PublicSharedpreferences;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;

public class Message_list_Activity extends BaseActivity {
	Spinner view;
	ImageView write;
	TextView title;
	ListView listView;
	Toolbar toolbar;
	TextView nodata;
	String[] httpcode = new String[6];
	PublicSharedpreferences ps;
	Data_Sharedpreferences.SF_Member member;
	Data_Sharedpreferences.SF_Student student;
	Message_List_Adapter adapter;
	Sqlite_Connect sc;
	private final int SUCCESS = 10;
	private final int FAIL = 9;
	private final int SUBSUCCESS = 8;
	private final int SUBFAIL = 7;
	int mode = 0;
	int count = 0;
	int rank = 0;
	boolean ListViewLock;
	ArrayList<WK_MESSAGE_LIST> list;
	public Sqlite_Connect sqlite_Connect;

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		switch (arg0) {
		case START_MESSAGE:
			if (arg1 == REFRESH_CODE) {
				startNetwork(1);
			}
			break;

		}
	}

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.message_list_activity);
		setToolbar();
		setStartData();
		
		registerReceiver(mToastMessageReceiver, new IntentFilter(
				"com.defysoft.waukids.TOAST_MESSAGE"));
	}

	@Override
	public void setStartData() {
		// TODO Auto-generated method stub
		super.setStartData();
		sqlite_Connect = new Sqlite_Connect(this);
		ps = new PublicSharedpreferences(this);
		ps.setMembersp();
		sc = new Sqlite_Connect(this);
		list = new ArrayList<WK_MESSAGE_LIST>();
		member = ps.getMembersp();
		rank = Integer.parseInt(member.Rank);
		write = (ImageView) findViewById(R.id.MASSEGE_LIST_WRITEBTN);
		title = (TextView) findViewById(R.id.MASSEGE_LIST_TITLE);

		listView = (ListView) findViewById(R.id.MASSEGE_LIST_LISTVIEW);
		nodata = (TextView) findViewById(R.id.MASSEGE_LIST_NODATA);
		httpcode[0] = CODE_MESSAGE_LIST_GETLIST;
		httpcode[1] = CODE_MESSAGE_LIST_GETLIST_YAC;
		httpcode[2] = CODE_MESSAGE_LIST_GETLIST_BACK;
		httpcode[3] = CODE_MESSAGE_LIST_GETPLUSLIST;
		httpcode[4] = CODE_MESSAGE_LIST_GETPLUSLIST_YAC;
		httpcode[5] = CODE_MESSAGE_LIST_GETPLUSLIST_BACK;

		if (!member.Rank.equals("3")) {
			write.setVisibility(View.GONE);
		} else {
			ps.setStudentsp();
			student = ps.getStudentsp();
			write.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					startActivityForResult(
							new Intent(Message_list_Activity.this,
									MessageMainWrite.class).putExtra("PK_Mem_Email", member.Email), START_MESSAGE);
				}
			});
		}

		startNetwork(1);
	}

	public void setToolbar() {
		toolbar = (Toolbar) findViewById(R.id.MASSEGE_LIST_TOOLBAR);
		// toggle세팅.
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		view = (Spinner) findViewById(R.id.MASSEGE_LIST_VIEW);
		view.setAdapter(new ArrayAdapter<String>(this, 0) {
			@Override
			public int getCount() {
				return 3;
			}

			@Override
			public View getDropDownView(int position, View convertView,
					ViewGroup parent) {
				final int pos = position;
				if (convertView == null) {
					convertView = getLayoutInflater().inflate(
							R.layout.overflowitem_row, null);
				}
				/*((TextView) convertView.findViewById(R.id.OVERFLOWITEM_TV))
				.setBackgroundColor(0x00ffffff);
					convertView.setBackgroundColor(0x00ffffff);*/
				

				switch (pos) {
				case 0:
					if (mode == 0) {
						convertView.setBackgroundColor(0xff37b34a);
					}
					((TextView) convertView.findViewById(R.id.OVERFLOWITEM_TV))
							.setText("전체보기");
					break;
				case 1:
					if (mode == 1) {
						convertView.setBackgroundColor(0xff37b34a);
					}
					((TextView) convertView.findViewById(R.id.OVERFLOWITEM_TV))
							.setText("투약의뢰서");
					break;
				case 2:
					if (mode== 2) {
						convertView.setBackgroundColor(0xff37b34a);
					}
					((TextView) convertView.findViewById(R.id.OVERFLOWITEM_TV))
							.setText("귀가동의서");
					break;

				}

				return convertView;
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				final int pos = position;
				if (convertView == null) {
					convertView = getLayoutInflater().inflate(
							R.layout.overflowitem_row, null);
				}
				((TextView) convertView.findViewById(R.id.OVERFLOWITEM_TV))
						.setBackgroundColor(0x00ffffff);
				return convertView;
			}
		});
		view.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				switch (position) {
				case 0: // 전체보기
					if (mode != 0) {
						mode = 0;
						startNetwork(1);
					}
					break;
				case 1: // 투약의뢰서
					if (mode != 1) {
						mode = 1;
						startNetwork(1);
					}
					break;
				case 2:	// 귀가동의서
					if (mode != 2) {
						mode = 2;
						startNetwork(1);
					}
					break;

				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}

		});
	}

	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			sqlite_Connect.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"Message_list_Activity", member.Email);			
			listView.setVisibility(View.VISIBLE);
			break;
		case SUCCESS:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			listView.setVisibility(View.VISIBLE);
			adapter = new Message_List_Adapter();
			listView.setAdapter(adapter);
			nodata.setVisibility(View.GONE);
			listView.setOnScrollListener(new OnScrollListener() {

				@Override
				public void onScrollStateChanged(AbsListView view,
						int scrollState) {
					// TODO Auto-generated method stub
				}

				@Override
				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
					// TODO Auto-generated method stub

					int lastItem = totalItemCount - visibleItemCount;
					if (firstVisibleItem >= lastItem && totalItemCount != 0
							&& ListViewLock == false) {
						if (list.size() < count) {
							ListViewLock = true;
							startNetwork(2);
						}
					}

				}
			});
			break;
		case FAIL:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			listView.setVisibility(View.GONE);
			nodata.setVisibility(View.VISIBLE);
			break;
		case SUBSUCCESS:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			listView.setVisibility(View.VISIBLE);
			adapter.notifyDataSetChanged();
			ListViewLock = false;
			break;
		case SUBFAIL:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			listView.setVisibility(View.VISIBLE);
			Toast.makeText(Message_list_Activity.this, "더이상 글이 없습니다.",
					Toast.LENGTH_SHORT).show();
			break;
		}
	}

	@Override
	public void startThread(int choice) {
		// TODO Auto-generated method stub
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				switch (cho) {
				case 1:
					mainThread();
					break;
				case 2:
					subThread();
					break;
				}
			}
		});
		firstThread.start();
	}

	public void mainThread() {
		String msg = "";
		JSONObject jsonObject;
		try {
			if (rank == 1) {
				jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
						"code=" + httpcode[mode] + "&sth=" + member.School));
			} else if (rank == 2) {
				jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
						"code=" + httpcode[mode] + "&sth=" + member.School
								+ "&class=" + member.Class));
			} else {
				jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
						"code=" + httpcode[mode] + "&sth=" + member.School
								+ "&class=" + student.Class + "&stu="
								+ student.Code));
			}
			if (jsonObject.getBoolean("success")) {
				msg = jsonObject.getString("payload");
				count = Integer.parseInt(jsonObject.getString("count"));
				list = JsonParser.Message_List_Parser(msg);
				onNetworkCallback(SUCCESS, "");
			} else {
				onNetworkCallback(FAIL, "");
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where mainThread()");
		}
		;
	}

	public void subThread() {
		String msg = "";
		JSONObject jsonObject;
		try {
			if (rank == 1) {
				jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
						"code=" + httpcode[mode + 3] + "&sth=" + member.School
								+ "&pk="
								+ list.get(list.size() - 1).PK_Mes_Code));
			} else if (rank == 2) {
				jsonObject = new JSONObject(publicHttpCallback(
						HTTP_URL,
						"code=" + httpcode[mode + 3] + "&sth=" + member.School
								+ "&class=" + member.Class + "&pk="
								+ list.get(list.size() - 1).PK_Mes_Code));
			} else {
				jsonObject = new JSONObject(publicHttpCallback(
						HTTP_URL,
						"code=" + httpcode[mode + 3] + "&sth=" + member.School
								+ "&class=" + student.Class + "&stu="
								+ student.Code + "&pk="
								+ list.get(list.size() - 1).PK_Mes_Code));
			}
			if (jsonObject.getBoolean("success")) {
				msg = jsonObject.getString("payload");
				list.addAll(JsonParser.Message_List_Parser(msg));
				onNetworkCallback(SUBSUCCESS, "");
			} else {
				onNetworkCallback(SUBFAIL, "");
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where subThread()");
		}
		;
	}

	class Message_List_Adapter extends ArrayAdapter<String> {

		public Message_List_Adapter() {
			super(Message_list_Activity.this, 0);
			// TODO Auto-generated constructor stub
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			Message_List_Holder holder;
			final int pos = position;
			if (convertView == null) {
				convertView = Message_list_Activity.this.getLayoutInflater()
						.inflate(R.layout.message_list_item, null);
				holder = new Message_List_Holder();
				holder.relativeLayout = (RelativeLayout)convertView
						.findViewById(R.id.message_list_item_rl);
				holder.from = (TextView) convertView
						.findViewById(R.id.message_list_item_from);
				holder.ok = (ImageView) convertView
						.findViewById(R.id.message_list_item_ok);
				holder.title = (TextView) convertView
						.findViewById(R.id.message_list_item_title);
				holder.toclass = (TextView) convertView
						.findViewById(R.id.message_list_item_toclass);
				holder.date = (TextView) convertView
						.findViewById(R.id.message_list_item_date);
				holder.newcheck = (ImageView) convertView
						.findViewById(R.id.message_list_item_new);
				convertView.setTag(holder);
			} else {
				holder = (Message_List_Holder) convertView.getTag();
			}
			holder.title
					.setText(list.get(position).Mes_Category.equals("1") ? "투약의뢰서"
							: "귀가동의서");
			holder.ok
					.setVisibility(list.get(position).Mes_Check.equals("0") ? View.GONE
							: View.VISIBLE);
			holder.toclass.setText("To : " + list.get(position).cla_name + " 선생님");
			holder.from.setText("From : " + list.get(position).stu_name
					+ " 보호자 " + list.get(position).Mes_Writer);
			holder.date.setText("Date : " + list.get(position).Mes_Date);
			/*holder.newcheck.setVisibility(sc.check_New_Massage(Integer
					.parseInt(list.get(pos).PK_Mes_Code)) ? View.GONE
					: View.VISIBLE);*/
			
			if (position%2 == 0) {
				holder.relativeLayout.setBackgroundColor(0x88ffffff);
			} else {
				holder.relativeLayout.setBackgroundColor(0x44ffffff);
			}

			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					sc.delete_New_Mas(Integer.parseInt(list.get(pos).PK_Mes_Code));

					startActivityForResult(

							new Intent(Message_list_Activity.this,
									Message_Detail_Activity.class).putExtra(
									"Mes_Category", list.get(pos).Mes_Category)
									.putExtra("PK_Mes_Code",
											list.get(pos).PK_Mes_Code).putExtra("Mem_Rank", member.Rank),
							START_MESSAGE);
				}
			});
			return convertView;
		}
	}

	class Message_List_Holder {
		RelativeLayout relativeLayout;
		TextView toclass;
		TextView from;
		TextView date;
		TextView title;
		ImageView ok;
		ImageView newcheck;
	}
	
	private final BroadcastReceiver mToastMessageReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			LinearLayout layout = (LinearLayout)getLayoutInflater().inflate(R.layout.toast_layout, null);
			TextView toast_tv = (TextView)layout.findViewById(R.id.TOAST_LAYOUT_TV);
			Toast toast = new Toast(Message_list_Activity.this);
			toast.setView(layout);
			toast_tv.setText(intent.getStringExtra("PUSH_NAME")+" : "+intent.getStringExtra("PUSH_SUB"));
			toast.setDuration(Toast.LENGTH_LONG);
			toast.show();
			startNetwork(1);
		}
	};

}
